package com.leo.basic.scheduler.quartz;

import com.leo.basic.scheduler.bean.SchedulerJob;
import com.leo.basic.scheduler.constant.SchedulerConstant;
import com.leo.basic.scheduler.service.ISchedulerJobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * @ClassName AbstractScheduleJob
 * @Description 主要用来记录每个定时任务的触发时间和执行时间
 * @Author wangss
 * @date 2021.09.22 21:55
 * @Version 1.0
 */
@Slf4j
public abstract class AbstractSchedulerJob extends QuartzJobBean {

    @Autowired
    private ISchedulerJobService schedulerJobService;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        // 记录任务开始时间
        Date startTime = new Date();
        SchedulerJob schedulerJob = (SchedulerJob) context.getMergedJobDataMap().get(SchedulerConstant.JOB_PARAM_KEY);
        log.info("jobName = [{}], jobGroup = [{}]", schedulerJob.getJobName(), schedulerJob.getJobGroup());
        String expMes = "";
        try {
            this.executeInternal(schedulerJob);
        } catch (Exception e) {
            expMes = e.getMessage();
            log.error("jobName = [{}] exec error, cause:{}", schedulerJob.getJobName(), expMes);
        }

        // 将任务执行信息入库
        schedulerJobService.schedulerSaveLog(schedulerJob, startTime, expMes);
    }

    public abstract void executeInternal(SchedulerJob schedulerJob) throws Exception;
}
